const express = require('express');
const router = express.Router();
const {getDb} = require('../dao/db'); // 导入数据库连接函数
const hashPwd = require('../utils/hashPwd'); // 导入密码哈希函数
const jwt = require('../utils/jwt'); // 导入 JWT 工具函数

router.post('/login', (req, res) => {

  let username = req.body.username;
  let password = req.body.password;

  if (!username || !password) {
    return res.status(400).json({ status:400,msg: '用户名和密码都不能为空' });
  }

  console.log("username:", username,"password:", password);
  
  let db = getDb();
  // 查询用户信息
  db.get("SELECT user_id, username, realname, password_hash FROM users WHERE username =?", username, (err, row) => {
    if (err || !row) {
      return res.status(401).json({ status:401,msg: '用户名不正确' });
    }	
    if (hashPwd(password)!= row.password_hash) {
      return res.status(401).json({ status:401,msg: '密码错误' });
    }
    // 生成JWT token
    let token = jwt.generateToken(row.user_id, row.realname);
    res.json({ status:0,msg: 'OK',token: token,user_id: row.user_id,realname: row.realname });

  })
  
});


router.post('/updateToken', (req, res) => {
  let token = req.body.token;
  if (!token) {
    return res.status(400).json({ status:400,msg: 'token不能为空' });
  }
  // 生成JWT token
  let tokenObj = jwt.refreshToken(token);
  if (!tokenObj.valid) {
    return res.status(401).json({ status:401,msg: 'token错误' });
  }

  res.json({ status:0,msg: 'OK',token: tokenObj.newToken });
  
});


module.exports = router;
